package com.practice.backend.Repository;

import com.practice.backend.Entity.User;
import com.practice.backend.Entity.UserSearchCriteria;
import jakarta.persistence.criteria.CriteriaBuilder;
import jakarta.persistence.criteria.CriteriaQuery;
import jakarta.persistence.criteria.Predicate;
import jakarta.persistence.criteria.Root;
import org.springframework.data.jpa.domain.Specification;

import java.util.ArrayList;
import java.util.List;

public class UserSpecification implements Specification<User> {
    private final UserSearchCriteria criteria;

    public UserSpecification(UserSearchCriteria criteria) {
        this.criteria = criteria;
    }

    @Override
    public Predicate toPredicate(Root<User> root, CriteriaQuery<?> query, CriteriaBuilder builder) {
        // 创建条件构造器
        List<Predicate> predicates = new ArrayList<>();

        // 动态添加条件  equal:精确查找  like：模糊查询（在查询字段加“%”）  in：包含关系
        if (criteria.getId() != null && !criteria.getId().isEmpty()) {
            predicates.add(builder.equal(root.get("id"), criteria.getId()));
        }
        if (criteria.getUsername() != null && !criteria.getUsername().isEmpty()) {
            predicates.add(builder.like(root.get("username"), "%" + criteria.getUsername() + "%"));
        }
        if (criteria.getSex() != null && !criteria.getSex().isEmpty()) {
            predicates.add(builder.equal(root.get("sex"), criteria.getSex()));
        }
        if (criteria.getAge() != null) {
            predicates.add(builder.equal(root.get("age"), criteria.getAge()));
        }
        if (criteria.getPhone() != null && !criteria.getPhone().isEmpty()) {
            predicates.add(builder.like(root.get("phone"), "%" + criteria.getPhone() + "%"));
        }
        if (criteria.getRankIds() != null && !criteria.getRankIds().isEmpty()) {
            predicates.add(root.get("rankId").in(criteria.getRankIds()));
        }
        if (criteria.getStatus() != null && !criteria.getStatus().isEmpty()) {
            predicates.add(builder.equal(root.get("status"), criteria.getStatus()));
        }

        // 返回条件，将所有条件以and起来
        // toArray(new Predicate[0])将列表转换为数组，并通过new Predicate[0]指定数组类型《Predicate数组》
        return builder.and(predicates.toArray(new Predicate[0]));
    }
}
